package com.ruoyi.project.mobile;


import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.R;
import com.ruoyi.common.utils.RFactory;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.system.coupon.coupon.domain.Coupon;
import com.ruoyi.project.system.coupon.coupon.service.ICouponService;
import com.ruoyi.project.system.coupon.usercoupon.domain.UserCoupon;
import com.ruoyi.project.system.coupon.usercoupon.dto.UserCouponDto;
import com.ruoyi.project.system.coupon.usercoupon.service.IUserCouponService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.service.IMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by HP on 2021/01/27.
 */
@RestController
@RequestMapping("/api/memberCoupon")
public class ApiMemberCouponController extends BaseController {

    @Autowired
    private IUserCouponService userCouponService;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private IMemberService memberService;


    /**
     * 查询优惠券列表
     * @param uid 用户主键ID
     * @return
     */
    @GetMapping("/getCouponList")
    public R getCouponList(@RequestParam String uid,
                           @RequestParam(required = false,defaultValue = "") Integer type,
                           @RequestParam(required = false,defaultValue = "") Integer status) {
        Member member = this.memberService.selectMemberById(uid);
        if (member==null) {
            return R.error("用户异常，请重新登录");
        }
        if (member.getIsVip() !=0 ) {
            return R.error("无");
        }
        startPage();
        Coupon coupon = new Coupon();
        coupon.setType(type);
        coupon.setStatus(status);
        coupon.setReceiveStatus(0);
        List<Coupon> coupons = this.couponService.selectCouponList(coupon);
        for(Coupon cou:coupons){
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setMemberId(uid);
            userCoupon.setCouponId(cou.getId());
            List<UserCouponDto> userCoupons = this.userCouponService.selectUserCouponList(userCoupon);
            //该用户是否领取过 0 未领取 1 已领取
            if(userCoupons.size()>0){
                cou.setReceiveStatus(1);
            }else{
                cou.setReceiveStatus(0);
            }
        }
        return RFactory.generateR(getDataTable(coupons));
    }

    /**
     * 首页提醒优惠券
     * @param uid 用户主键ID
     * @return
     */
    @GetMapping("/getIndexCoupon")
    public R getIndexCoupon(@RequestParam String uid) {
        Member member = this.memberService.selectMemberById(uid);
        if (member.getIsVip() !=0 ) {
            return R.error("无");
        }
        Coupon coupon = new Coupon();
        coupon.setIsShow(1);
        coupon.setReceiveStatus(0);
        List<Coupon> coupons = this.couponService.selectCouponList(coupon);
        for(Coupon cou:coupons){
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setMemberId(uid);
            userCoupon.setCouponId(cou.getId());
            List<UserCouponDto> userCoupons = this.userCouponService.selectUserCouponList(userCoupon);
            //该用户是否领取过 0 未领取 1 已领取
            if(userCoupons.size()>0){
                cou.setReceiveStatus(1);
            }else{
                cou.setReceiveStatus(0);
            }
        }
        return RFactory.generateR(coupons);
    }

    /**
     * 领取优惠券
     * @param userCoupon
     * @return
     */
    @PostMapping("/saveMyCoupon")
    @Transactional
    public R saveMyCoupon(@RequestBody UserCoupon userCoupon) {
        Coupon coupon = this.couponService.selectCouponById(userCoupon.getCouponId());
        //判断优惠券数量是否为0
        if(coupon.getTotal()==0){
            return R.error("您来晚了,被抢光了..");
        }
        //判断是否领取过
        UserCoupon oldCoupon = new UserCoupon();
        oldCoupon.setMemberId(userCoupon.getMemberId());
        oldCoupon.setCouponId(userCoupon.getCouponId());
        List<UserCouponDto> userCoupons = this.userCouponService.selectUserCouponList(userCoupon);
        if(userCoupons.size()>0){
            return R.error("你已领取过");
        }else{
            //更新优惠券数量
            Coupon update = new Coupon();
            update.setId(coupon.getId());
            update.setTotal(coupon.getTotal()-1);
            update.setSendNum(coupon.getSendNum()+1);
            this.couponService.updateCoupon(update);
            //添加用户优惠券
            userCoupon.setStatus(0);
            userCoupon.setType(coupon.getType());
            userCoupon.setStartTime(coupon.getStartTime());
            userCoupon.setNotes(coupon.getNotes());
            userCoupon.setEndTime(coupon.getEndTime());
            userCoupon.setPrice(coupon.getPrice());
            userCoupon.setEnoughMoney(coupon.getEnoughMoney());
            userCoupon.setUseCondition(coupon.getUseCondition());
            userCoupon.setName(coupon.getName());
            userCoupon.setCreated(DateUtils.getNowDate());
            this.userCouponService.insertUserCoupon(userCoupon);
            return R.ok();
        }
    }

    /**
     * 查询我能用的的优惠券列表
     * @param uid 用户主键ID
     * @param type: 优惠券类型：0 满减券 1 抵扣券
     * @param status 优惠券状态（0-未使用，1-已使用，2-已过期，3-已失效）
     * @param orderPrice 查询用 订单价格
     * @return
     */
    @ResponseBody
    @RequestMapping("/getMyCouponList")
    public R getMyCouponList(@RequestParam String uid,
                             @RequestParam(required = false,defaultValue = "") Integer type,
                             @RequestParam(required = false,defaultValue = "") Integer status,
                             @RequestParam(required = false) BigDecimal orderPrice) {
        Member member = this.memberService.selectMemberById(uid);
        if (member==null) {
            return R.error("用户异常，请重新登录");
        }
        if (member.getIsVip() !=0 ) {
            return R.error("无");
        }
        startPage();
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setMemberId(uid);
        userCoupon.setType(type);
        userCoupon.setStatus(status);
        userCoupon.setOrderPrice(orderPrice);
        return RFactory.generateR(getDataTable(this.userCouponService.selectUserCouponList(userCoupon)));
    }

//    /*
//   * 查询我能用的的优惠券列表
//   * */
//    @ResponseBody
//    @RequestMapping("/getMyCanCouponList")
//    public R getMyCanCouponList(@RequestBody Map<String,Object> paramMap) {
//        try{
//            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
//                    ||!paramMap.containsKey("payment") || StringUtils.isBlank(paramMap.get("payment").toString())
//                    ) {
//                return R.error("参数错误");
//            }
//            paramMap.put("type","0");
//            PageInfo<Map<String,Object>> map = memberCouponService.getMyCouponList(paramMap);
//            return R.ok().put("data", map);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return R.error("查询失败");
//        }
//    }


}
